package com.us.core;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.us.tag.BaseArgs;

/**
 * 大文件压缩过滤器
 * 
 * @author monlyu
 */
public class GzipFilter implements Filter {

    Map<String, String> heads = new HashMap<String, String>();

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
        if (req instanceof HttpServletRequest) {
            doFilter((HttpServletRequest) req, (HttpServletResponse) rsp, chain);
        } else {
            chain.doFilter(req, rsp);
        }
    }

    /**
     * 过滤操作
     */
    public void doFilter(HttpServletRequest req, HttpServletResponse rsp, FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");
        for (String key : heads.keySet()) {
            rsp.addHeader(key, heads.get(key));
        }
        chain.doFilter(req, rsp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        String headStr = config.getInitParameter("headers");
        String[] headers = headStr.split(",");
        for (String head : headers) {
            String[] temp = head.split("=");
            heads.put(temp[0].trim(), temp[1].trim());
        }
        if (!BaseArgs.DEV_MODEL) {
//            heads.put("Cache-Control", "max-age=2678400000");
//            heads.put("Etag", BaseArgs.CACHE_VERSION);
        }
    }
}
